<?php

namespace app\mp\admin;

use app\system\admin\Admin;
use app\common\service\TProject as TProjectService;
/**
 * 项目管理
 * @author 飞燕
 *
 */
class TProject extends Admin
{
    protected $hisiModel = 'TProject';//模型名称[通用添加、修改专用]
    protected $hisiValidate = 'TProject';
    protected $hisiAddScene = '';//添加数据验证场景名
    protected $hisiEditScene = '';//更新数据验证场景名

    public function initialize() {
    	parent::initialize();
    }
    /**
     * 项目列表
     * @author 飞燕
     * @date 2020年8月21日
     */
    public function index()
    {
        $tProjectService=new TProjectService();
        if ($this->request->isAjax()) {
            $keyword    = $this->request->param('keyword/s');
            $where      = $data = [];
            if ($keyword) {
                $where[] = ['name', 'like', "%{$keyword}%"];
            }
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 20);
            $order = 'id desc';
            $systemUserKV = getSystemUserKV(null);
            $projectData = db('t_project tp')->field('tp.*')
                ->where($where)->page($page)->limit($limit)->order($order)->select();
            //->join('t_project_user pro_user', "pro_user.project_id=tp.id and pro_user.type=1", 'left')audit_id
            $projectTaskCounts=db("t_task")->where([['project_id', 'in', array_column($projectData,'id')],['status','<',99]])
                ->group("project_id")->column("count(id) as all_count,sum(case when status=3 then 1 else 0 end) as finish_count","project_id"); //查询项目下的任务进行数完成数
            foreach ($projectData as $key => $value) {
            	$projectUserList = $tProjectService->getUsersByProjectId($value['id']);
                $value['userAll'] = implode('、', array_values($projectUserList));
                $value['nick']=arrayGet($systemUserKV, $value['admin_id']);
                $value['audit_id_name']=db('t_project_user pu')->where([['project_id','eq',$value['id']],['type','eq',1]])
                    ->join('system_user suser',"pu.admin_id=suser.id")->column('nick');
                $value['audit_id_name']=count($value['audit_id_name'])>0 ? implode(',',$value['audit_id_name']) : $value['audit_id_name'];
                $value['all_task_count']=isset($projectTaskCounts[$value['id']]) ? $projectTaskCounts[$value['id']]['all_count'] : 0;
                $value['finish_task_count']=isset($projectTaskCounts[$value['id']]) ? $projectTaskCounts[$value['id']]['finish_count'] : 0;
                $data['data'][]=$value;
            }
            $data['count'] = db('t_project')->where($where)->count('id');
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
    	}
    	$assign = [];
    	return $this->assign($assign)->fetch();
    }

    public function del(){
        $id = $this->request->param('id/a');
        if (empty($id)) {
            return $this->error('缺少id参数');
        }
        $projectinfo=db('t_project')->find($id);
        $ret=db('t_project')->where(['id' => $id])->update(['status'=>$projectinfo['status'] == 99 ? 1 :99 ]);
        echo"<script>history.go(-1);</script>";
        return;
    }

    /**
     * 设置成员
     * @author sparkguo
     * @date 2020年8月22日
     */
    public function setProjectUser() {
        $tProjectService=new TProjectService();
        $projectId = $this->request->param('projectId/d', 0);
        $userNum = $this->request->param('userNum/s', '');
        $project_users = $this->request->param('project_users/s', ''); //项目成员
        $audit_users = $this->request->param('audit_users/s', '');
        if ($this->request->isPost()) {
        	try {
        		db()->startTrans();
                $project_users=explode(",",$project_users);
                $audit_users=explode(",",$audit_users);
                if(count($project_users)>0){ //删除旧的项目成员
                    db('t_project_user')->where([['project_id','eq',$projectId],['type','eq',2],['admin_id','not in',$project_users]])->delete();
                }
                if(count($audit_users)>0){
                    db('t_project_user')->where([['project_id','eq',$projectId],['type','eq',1],['admin_id','not in',$audit_users]])->delete();
                }
                foreach ($project_users as $key => $value) { //拼接到userinfo里做批量新增
                    $userInfo[]=$value."/".'2';
                }
                foreach ($audit_users as $key => $value) {
                    $userInfo[]=$value."/".'1';
                }
        		foreach ($userInfo as $key => $value) {
        			$value1=explode("/",$value);
        			$where = [
        				'project_id'=>$projectId,
        				'admin_id'=>$value1[0],'type'=> $value1[1],
        			];
        			$info = db('t_project_user')->where($where)->find();
        			if (empty($info)) {
        				$insData = $where;
        				$insData['type'] = $value1[1];
        				$insData['create_time'] = time();
        				$insData['update_time'] = time();
        				db('t_project_user')->insert($insData);
        			} else{
        				$upData = $where;
        				$upData['type'] = $value1[1];
        				$upData['update_time'] = time();
        				db('t_project_user')->where('id', $info['id'])->update($upData);
        			}
        		}
        		db()->commit();

        		return $this->Json(1);
        	} catch (\Exception $e) {
        		db()->rollback();
        		return $this->Json(0, '保存失败，'. $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
        	}

        }
        $assign = [];
        $assign['projectId']=$projectId;
        $userData = getSystemUserKV(1);
        $project_users=db('t_project_user')->where([['project_id','eq',$projectId],['type','eq',2]])->column('admin_id');
        $audit_users=db('t_project_user')->where([['project_id','eq',$projectId],['type','eq',1]])->column("admin_id");

        foreach ($userData as $key => $value) {
            $auditUser=$otherUser=['name'=>$value,'value'=>$key];
            if(is_array($audit_users) && in_array($key,$audit_users)){
                $auditUser['selected']=true;
            }
            if(is_array($project_users) && in_array($key,$project_users)){
                $otherUser['selected']=true;
            }
            $assign['auditUsers'][]=$auditUser;
            $assign['projectUsers'][]=$otherUser;
        }
        $template = $this->request->param('template', 'set_project_user');
        return $this->assign($assign)->fetch($template);
    }
    /**
     * 添加项目
     * @author 飞燕
     * @date 2020年8月22日
     */
    public function add() {
        if ($this->request->isPost()) {
            $name = $this->request->param('name/s', '');
            $remark = $this->request->param('remark/s', '');
            try {
                db()->startTrans();
                $projectData=[
                    'name'=>$name,
                    'remark'=>$remark,
                    'create_time' => time(),
                    'update_time' => time(),
                    'admin_id'=>ADMIN_ID,
                ];
                $projectId= db('t_project')->insertGetId($projectData);
                $tProjectService = new TProjectService();
                $projectUserData=[
                    'project_id'=>$projectId,
                    'admin_id'=>ADMIN_ID,
                    'type'=>1,
                    'create_time' => time(),
                    'update_time' => time(),
                ];
                //同步数据
                db('t_project_user')->insert($projectUserData);
                db()->commit();
                return $this->Json(1, '保存成功');
            } catch (\Exception $e) {
                db()->rollback();
                return $this->Json(0, '保存失败，'. $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
            }
        }
        $assign = [];
    	$template = $this->request->param('template', 'form');
    	return $this->assign($assign)->fetch($template);

    }
}

